package main

import (
	"elegantGo/chapter02-1/oo"
	"elegantGo/chapter02-1/pkg/validate"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"net/http"
)

func main() {

	validate.RegisterValidation("phone", func(fl validator.FieldLevel) bool {
		var phone oo.Phone
		phone.SetValue(fl.Field().String())
		return phone.IsValid()
	})

	validate.RegisterValidation("code", func(fl validator.FieldLevel) bool {
		var code oo.Code
		code.SetValue(fl.Field().String())
		return code.IsValid()
	})

	validate.RegisterValidation("nickname", func(fl validator.FieldLevel) bool {
		var nickname oo.Nickname
		nickname.SetValue(fl.Field().String())
		return nickname.IsValid()
	})

	validate.RegisterValidation("password", func(fl validator.FieldLevel) bool {
		var password oo.Password
		password.SetValue(fl.Field().String())
		return password.IsValid()
	})

	srv := gin.Default()

	srv.POST("/sms/send", func(c *gin.Context) {
		type SmsSend struct {
			Phone string `binding:"phone"`
		}
		req := new(SmsSend)
		if err := c.ShouldBind(req); err != nil {
			c.JSON(http.StatusOK, err.Error())
			return
		}
		c.JSON(http.StatusOK, req)
	})

	srv.POST("/user/register", func(c *gin.Context) {
		type UserRegister struct {
			Phone      string `binding:"phone"`
			Code       string `binding:"code"`
			Nickname   string `binding:"nickname"`
			Password   string `binding:"password"`
			RePassword string `binding:"eqfield=Password"`
		}

		req := new(UserRegister)
		if err := c.ShouldBind(req); err != nil {
			c.JSON(http.StatusOK, err.Error())
			return
		}
		c.JSON(http.StatusOK, req)
	})

	srv.POST("/user/sms/login", func(c *gin.Context) {
		type UserSmsLogin struct {
			Phone string `binding:"phone"`
			Code  string `binding:"code"`
		}

		req := new(UserSmsLogin)
		if err := c.ShouldBind(req); err != nil {
			c.JSON(http.StatusOK, err.Error())
			return
		}
		c.JSON(http.StatusOK, req)
	})

	srv.POST("/user/password/login", func(c *gin.Context) {
		type UserPasswordLogin struct {
			Phone    string `binding:"phone"`
			Password string `binding:"password"`
		}

		req := new(UserPasswordLogin)
		if err := c.ShouldBind(req); err != nil {
			c.JSON(http.StatusOK, err.Error())
			return
		}
		c.JSON(http.StatusOK, req)
	})
	srv.Run(":80")
}
